<?php


namespace app\app\controller;
define('POINTS_DAY_CHECKIN', 10);
define('POINTS_INVITATE', 100);

define('LOG_TYPE_INVITATION', 'invitation');
define('LOG_TYPE_CHECKIN', 'checkin');//签到
define('LOG_TYPE_REDEEM', 'redeem');//兑换
define('LOG_TYPE_REVIEW', 'review');//好评免广告
class Device extends Base
{
    public $redeemList = [
        1 => [
            'id' => 1,
            'type' => 'week',
            'name' => '一周',
            'points' => 200,
        ],
        2 => [
            'id' => 2,
            'type' => 'month',
            'name' => '一月',
            'points' => 600
        ],
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 得到设备邀请、积分、VIP信息
     * @param false $return
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($return = false)
    {
        $appId = input('app_id');
        $deviceId = input('device_id');
        if (empty($appId) || empty($deviceId)) {
            $this->error('数据有误！');
        }
        $deviceInfo = db('device')->where('app_id', $appId)->where('device_id', $deviceId)->field('app_id,device_id,code,invitation_code,points,time_expired')->find();
        if (empty($deviceInfo)) {
            $this->error('没有找到相应的信息');
        }
        if (empty($deviceInfo['code'])) {
            $codeIsUsed = true;
            while ($codeIsUsed) {
                try {
                    $code = $this->createCode();
                    db('device')->where('app_id', $appId)->where('device_id', $deviceId)->update(['code' => $code]);
                    $codeIsUsed = false;
                    $deviceInfo['code'] = $code;
                } catch (\Exception $e) {
                    $codeIsUsed = true;
                }
            }
        }
        if($deviceInfo['time_expired']<=time()){
            $deviceInfo['time_expired']=0;
        }

        if ($deviceInfo['time_expired'] > 0) {
            $deviceInfo['time_expired_text'] = date('Y-m-d H:i:s', $deviceInfo['time_expired']);
        } else {
            $deviceInfo['time_expired_text'] = '';
        }
        //检查是否签到
        $checkStatus = db('checkin')->where('date', date('Y-m-d'))->where('app_id', $appId)->where('device_id', $deviceId)->count();
        if ($checkStatus > 0) {
            $deviceInfo['isCheckedIn'] = true;
        } else {
            $deviceInfo['isCheckedIn'] = false;
        }
        if ($return) {
            return $deviceInfo;
        }
        $this->success('获取成功', $deviceInfo);

    }

    protected function createCode()
    {
        return str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
    }

    /**
     * 每日签到
     * @throws \think\exception\PDOException
     */
    public function checkIn()
    {
        $appId = input('app_id');
        $deviceId = input('device_id');
        if (empty($appId) || empty($deviceId)) {
            $this->error('数据有误！');
        }
        $time = time();
        $date = date('Y-m-d', $time);
        db()->startTrans();
        try {
            db('checkin')->insertGetId([
                'app_id' => $appId,
                'device_id' => $deviceId,
                'date' => $date,
                'time_added' => $time
            ]);
            addLog($appId, $deviceId, POINTS_DAY_CHECKIN,  '签到获得' . POINTS_DAY_CHECKIN . '积分', LOG_TYPE_CHECKIN, $date, $time);
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            $this->error('签到失败，您已经签过到了！');
        }
        $deviceInfo = $this->getInfo(true);
        $this->success('签到成功！', $deviceInfo);
    }

    /**
     * 绑定邀请码
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bindInvitationCode()
    {
        $appId = input('app_id');
        $deviceId = input('device_id');
        $code = input('code');
        if (empty($appId) || empty($deviceId) || empty($code)) {
            $this->error('数据有误！');
        }
        $invitationInfo = db('device')->where('code', $code)->find();
        if (empty($invitationInfo)) {
            $this->error('邀请码有误！');
        }
        $deviceInfo = db('device')->where('app_id', $appId)->where('device_id', $deviceId)->find();
        if (!empty($deviceInfo['invitation_code'])) {
            $this->error('您已经添加过邀请人了');
        }
        if($code == $deviceInfo['code']){
            $this->error('您不能邀请自己！');
        }
        if ($invitationInfo['invitation_code'] == $deviceInfo['code']) {
            $this->error('邀请人添加失败，您不能与邀请人相互邀请');
        }
        db()->startTrans();
        try {
            $time = time();
            $date = date('Y-m-d', $time);
            db('device')->where('code', $deviceInfo['code'])->update(['invitation_code' => $code]);
            addLog($invitationInfo['app_id'], $invitationInfo['device_id'], POINTS_INVITATE, '邀请' . $deviceInfo['code'] . '的用户加入，获得 ' . POINTS_INVITATE . ' 积分', LOG_TYPE_INVITATION, $date, $time);
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            $this->error('添加邀请人失败！');
        }

        $this->success('操作成功!');
    }

    /**
     * 兑换列表
     */
    public function getRedeemList()
    {
        $this->success('获取成功', array_values($this->redeemList));
    }

    /**
     * 兑换VIP
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function redeem()
    {
        $id = input('id', 0, 'intval');
        $appId = input('app_id');
        $deviceId = input('device_id');
        if ($id < 1 || empty($appId) || empty($deviceId)) {
            $this->error('数据有误！');
        }

        if (!isset($this->redeemList[$id])) {
            $this->error('数据有误！');
        }

        $redeemInfo = $this->redeemList[$id];
        $deviceInfo = db('device')->where('app_id', $appId)->where('device_id', $deviceId)->field('app_id,device_id,code,invitation_code,points,time_expired')->find();
        if ($deviceInfo['time_expired'] > time()) {
            $this->error('您已经屏蔽广告了，请在有效期结束后再来兑换！');
        }
        if ($deviceInfo['points'] < $redeemInfo['points']) {
            $this->error('积分不足，无法兑换');
        }
        $time = time();
        $date = date('Y-m-d', $time);
        $timeText = $this->getTimeText($redeemInfo);
        if ($timeText === false) {
            $this->error('数据出错！');
        }
        $expired_time = strtotime($timeText);
        db()->startTrans();
        try {

            db('device')->where('app_id', $appId)->where('device_id', $deviceId)->update([
                'time_expired' => $expired_time
            ]);
            addLog($appId, $deviceId, -$redeemInfo['points'],  '兑换 ' . $redeemInfo['name'] . ' 花费 ' . $redeemInfo['points'] . ' 积分', LOG_TYPE_REDEEM, $date, $time);
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            $this->error('兑换失败，请重试！');
        }
        $deviceInfo = $this->getInfo(true);
        $this->success('兑换' . $redeemInfo['name'] . '成功', $deviceInfo);


    }

    protected function getTimeText($redeemInfo)
    {
        switch ($redeemInfo['type']) {
            case 'week':
                $timeText = '+1 week';
                break;
            case 'month':
                $timeText = '+1 month';
                break;
            default:
                $timeText = false;
        }

        return $timeText;
    }

    public function getPointsLog()
    {
        $appId = input('app_id');
        $deviceId = input('device_id');
        if (empty($appId) || empty($deviceId)) {
            $this->error('数据有误！');
        }

        $list = db('points')->where('app_id', $appId)->where('device_id', $deviceId)->order('time_added','desc')->paginate(20)->each(function ($item) {
            $item['time_added_text'] = date('Y-m-d H:i:s', $item['time_added']);
            return $item;
        });
        $this->success('获取成功！', [
            'listRows' => $list->listRows(),
            'lastPage' => $list->lastPage(),
            'currentPage' => $list->currentPage(),
            'total'=>$list->total(),
            'list'=>$list->items()
        ]);
    }

    public function instruction(){
        $this->success('获取成功',[
            '每天签到可以获得'.POINTS_DAY_CHECKIN.'积分',
            '邀请1个好友可以获得'.POINTS_INVITATE.'积分',
        ]);
    }
}

